package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.heima.common.exception.CustException;
import com.heima.model.admin.dtos.AdUserDTO;
import com.heima.model.admin.pojo.AdUser;
import com.heima.model.admin.vo.AdUserVO;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;

@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService{

    @Override
    public ResponseResult login(AdUserDTO userDTO) {
        //1 参数校验
        if (StringUtils.isBlank(userDTO.getName())||StringUtils.isBlank(userDTO.getPassword())){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"参数错误");
        }
        //2 根据用户名查询用户信息
        AdUser adUser = getOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, userDTO.getName()));
        if (adUser == null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"用户不存在");
        }
        //3 获取数据库密码和盐， 匹配密码
        String salt = adUser.getSalt();
        String s = DigestUtils.md5DigestAsHex((userDTO.getPassword() + salt).getBytes());//输入的密码
        if (!adUser.getPassword().equals(s)){
            CustException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        //判断用户状态
        if (adUser.getStatus().intValue() != 9){
            CustException.cust(AppHttpCodeEnum.LOGIN_STATUS_ERROR);
        }
        //4 修改登录时间
        adUser.setLoginTime(new Date());
        updateById(adUser);
        //5 颁发token jwt 令牌
        String token = AppJwtUtil.getToken(Long.valueOf(adUser.getId()));
        // 用户信息返回 VO
        HashMap result = new HashMap<>();
        AdUserVO adUserVO = new AdUserVO();
        //将一个对象数据复制到另一个对象(字段一致),只给前端需要的数据
        BeanUtils.copyProperties(adUser,adUserVO);
        //6 返回结果（jwt）
        result.put("token",token);
        result.put("user",adUserVO);
        return ResponseResult.okResult(result);
    }
}
